package com.travelgroup.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.travelgroup.domain.entity.PaymentOrder;
import com.travelgroup.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Map;

@Component
@Slf4j
public class AliPayUtil {
    @Resource
    private Config config;

    /**
     * 费用支付
     * @param groupTitle
     * @param orderNo
     * @param amount
     * @return
     */
    public Map<String, Object> pay(String groupTitle, String orderNo, String amount) {
        try {

            // 连接网关
            Factory.setOptions(config);

            // 面对面方式进行支付，提供旅游名称，订单号，费用等信息
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                    .preCreate(groupTitle, orderNo, amount);

            // 对响应结果进行解析，将json数据转为json对象
            String httpBody = response.getHttpBody();
            JSONObject jsonObject = JSONUtil.parseObj(httpBody);

            // 利用hutool包工具从json对象中获取支付二维码URL
            String qrUrl = jsonObject.getJSONObject("alipay_trade_precreate_response")
                    .getStr("qr_code");
            BufferedImage qrCodeImage = QrCodeUtil.generate(qrUrl, 300, 300);

            // 将二维码URL转为Base64传递给前端
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(qrCodeImage, "png", os);
            String base64QRCode = Base64.getEncoder().encodeToString(os.toByteArray());

            // 构建返回数据
            return Map.of(
                    "orderNo", orderNo,
                    "qrCode", "data:image/png;base64," + base64QRCode,
                    "qrUrl", qrUrl  // 原始二维码URL，备用
        );} catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 退款操作
     * @param paymentOrder
     * @return
     */
    public boolean refund(PaymentOrder paymentOrder) {
        try {
            // 连接网关
            Factory.setOptions(config);

            // 执行退款操作，发送订单号以及费用
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(paymentOrder.getOrderNo(),
                    paymentOrder.getAmount().toString());
            // 检查响应码是否完成退款
            if ("10000".equals(response.code)) {
                log.info("支付宝退款成功");
                return true;
            } else {
                log.error("支付宝退款查询失败: {} - {}", response.code, response.msg);
                return false;
            }
        } catch (Exception e) {
            log.info("支付宝支付异常");
            throw new BusinessException("支付宝支付异常" + e.getMessage());
        }
    }
}
